package com.cskaoyan.user.service.impl;

import com.cskaoyan.mall.commons.exception.BizException;
import com.cskaoyan.mall.commons.exception.ExceptionProcessorUtils;
import com.cskaoyan.user.constants.UserRetCode;
import com.cskaoyan.user.dal.entitys.Member;
import com.cskaoyan.user.dal.entitys.UserVerify;
import com.cskaoyan.user.dal.persistence.MemberMapper;
import com.cskaoyan.user.dal.persistence.UserVerifyMapper;
import com.cskaoyan.user.dto.UserVerifyResponse;
import com.cskaoyan.user.service.IVerifyService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import java.util.List;

/**
 * @author chenai
 * @description TODO
 * @date 2022-06-20 10:49
 */
@Service
@Slf4j
public class IVerifyServiceImpl implements IVerifyService {
    @Autowired
    UserVerifyMapper userVerifyMapper;

    @Autowired
    MemberMapper memberMapper;

    @Transactional
    @Override
    public UserVerifyResponse verify(String uuid, String username) {
//        long id = Long.parseLong(uuid);
        UserVerifyResponse response = new UserVerifyResponse();
        try {
            //根据用户id和用户名修改用户状态
            Example example = new Example(UserVerify.class);
            Example.Criteria criteria = example.createCriteria();
            criteria.andEqualTo("uuid", uuid);
            criteria.andEqualTo("username", username);
            UserVerify userVerify = new UserVerify();
            userVerify.setIsVerify("Y");
            int userVerifyRows = userVerifyMapper.updateByExampleSelective(userVerify, example);
            if(userVerifyRows != 1){
                throw new BizException(UserRetCode.USERVERIFY_INFOR_INVALID.getCode(),
                        UserRetCode.USERVERIFY_INFOR_INVALID.getMessage());
            }
            // 修改member表
            Example memberExample = new Example(Member.class);
            memberExample.createCriteria().andEqualTo("username", username);
            Member member = new Member();
            member.setIsVerified("Y");
            int effectedRows = memberMapper.updateByExampleSelective(member, memberExample);
            if(effectedRows != 1){
                throw new BizException(UserRetCode.USERVERIFY_INFOR_INVALID.getCode(),
                        UserRetCode.USERVERIFY_INFOR_INVALID.getMessage());
            }
            //返回数据
            response.setCode(UserRetCode.SUCCESS.getCode());
            response.setMsg(UserRetCode.SUCCESS.getMessage());
        }catch (Exception e){
            e.printStackTrace();
            ExceptionProcessorUtils.wrapperHandlerException(response, e);
        }

        return response;
    }
}
